package com.weixiaodong.ModelDesign.生成实例.Singleton模式.练习.指定上限个数;

import com.sun.xml.internal.xsom.impl.scd.Iterators;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

// 采用懒汉式的单例模式，即延迟创建
@SuppressWarnings("all")
public class Triple {

    private static final Triple[] triples = new Triple[3];

    private static final ReentrantLock lock = new ReentrantLock();

    private static volatile int created = 0; // 记录当前创建的对象的个数

    private static final int MAX_SINLETONS = 3;

    private static int id;

    private Triple() {};

    private Triple(int id) {
        System.out.println("created triple-" + id);
    }

    public static Triple getInstance() {
        if (created == MAX_SINLETONS) {
            lock.lock();
            id++;
            id %= MAX_SINLETONS;
            lock.unlock();
            return triples[id];
        }
        Triple triple = new Triple(created);
        triples[created] = triple;
        lock.lock();
        created++;
        lock.unlock();
        return triple;
    }

    public static void main(String[] args) {
        Triple instance1 = Triple.getInstance();
        Triple instance2 = Triple.getInstance();
        Triple instance3 = Triple.getInstance();
        Triple instance4 = Triple.getInstance();
        Triple instance5 = Triple.getInstance();
        System.out.println(instance1);
        System.out.println(instance2);
        System.out.println(instance3);
        System.out.println(instance4);
        System.out.println(instance5);
    }

}
